#include"client.h"
#include"util.h"
#include<sys/socket.h>
#include<arpa/inet.h>
#include<string.h>
#include<stdlib.h>
#include<sys/epoll.h>
int tcpConnection(const char *ip,const char *port)
{
    int clientFd = socket(AF_INET,SOCK_STREAM,0);
    errif(clientFd == -1,"socket create error");
    
    struct sockaddr_in serverAddr;
    memset(&serverAddr, 0, sizeof(serverAddr));
    serverAddr.sin_family = AF_INET;
    serverAddr.sin_port = htons(atoi(port));
    serverAddr.sin_addr.s_addr = inet_addr(ip);

    int connetRet = connect(clientFd,(struct sockaddr*)&serverAddr,sizeof(serverAddr));
    errif(connetRet < 0 ,"connect error");

    return clientFd;
}

int epollAdd(int epfd,int fd)
{
    struct epoll_event ev;
    ev.data.fd = fd;
    ev.events = EPOLLIN;
    int epoll_ctl_res = epoll_ctl(epfd,EPOLL_CTL_ADD,fd,&ev);
    errif(epoll_ctl_res == -1,"epoll add error");
    return 0;
}

int recvn(int sockfd, void *buf, int len) {
    int left = len;
    char *p =(char *)buf;
    while (left > 0) {
        int ret = recv(sockfd, p, left, 0); 
        if (ret < 0) {
            perror("recvn error");
            return -1; // 错误处理
        } else if (ret == 0) {
            break; // 如果返回0，则表示连接被关闭
        }
        left -= ret;
        p += ret;
    }
    return len - left; // 返回实际接收的字节数
}

int sendn(int sockfd, const void *buf, int len) {
    int left = len;
    const char *p =(char *) buf;
    while (left > 0) {
        int ret = send(sockfd, p, left, 0);
        if (ret < 0) {
            perror("sendn error");
            return -1; // 错误处理
        }
        left -= ret;
        p += ret;
    }
    return len; // 返回发送的字节数
}

int parseCommand(const char * command,int len,train_t *pt)
{
    char *pstrs[10] = {0};
    int cnt = 0;
    //分割命令
    splitString(command," ",pstrs,10,&cnt);
    pt->taskType = getCommandType(pstrs[0]);
    if (cnt > 1) {
	    pt->_length = strlen(pstrs[1]);
	    strncpy(pt->_data, pstrs[1], pt->_length);
    }
    return 0;
}
int getCommandType(const char *str)
{
	if (!strcmp(str, "pwd"))
		return CMD_TYPE_PWD;
	else if (!strcmp(str, "ls"))
		return CMD_TYPE_LS;
	else if (!strcmp(str, "cd"))
		return CMD_TYPE_CD;
	else if (!strcmp(str, "mkdir"))
		return CMD_TYPE_MKDIR;
	else if (!strcmp(str, "rmdir"))
		return CMD_TYPE_RMDIR;
	else if (!strcmp(str, "puts"))
		return CMD_TYPE_PUTS;
	else if (!strcmp(str, "gets"))
		return CMD_TYPE_GETS;
	else
		return 0;
}

int putsCommand(clientTLV *pt)
{
	FileData file_data;

    pthread_t pid;
    
}
